package com.moyu.admin.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/** 登录控制器 */
@Controller
@RequestMapping("/")
@Slf4j
public class LoginController {

  @GetMapping("/login")
  public String login() {
    return "login";
  }

  @PostMapping("/login")
  public String doLogin(String username, String password) {
    String error = null;
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    try {
      subject.login(token);
      log.error("loginSuccess! Welcome: {} !", username);
    } catch (UnknownAccountException e) {
      log.error("loginError! username: {} , password: {}", username, password);
      log.error("UnknownAccountException: ", e);
    } catch (IncorrectCredentialsException e) {
      log.error("loginError! username: {} , password: {}", username, password);
      log.error("IncorrectCredentialsException: ", e);
    } catch (AuthenticationException e) {
      log.error("loginError! username: {} , password: {}", username, password);
      log.error("AuthenticationException: ", e);
    }

    if (error != null) {
      return "login";
    } else {
      return "redirect:/";
    }
  }
}
